<script setup>
import {
  NIcon,
  NEmpty,
  NSpin,
  NThing,
  NConfigProvider,
  useModal,
  NText,
  NButton,
  NFlex,
  NCollapse,
  NCollapseItem,
  NList,
  NListItem,
  NLoadingBarProvider,
  useMessage,
  NDataTable,
  NGrid,
  NGi,
  NInfiniteScroll,
  NModal,
  NDrawer,
  NDrawerContent,
  useDialog,
  NAlert,
  NInput
} from 'naive-ui'
import { AlertCircleSharp } from '@vicons/ionicons5'
import {
  FolderOpen20Regular as FolderOpen,
  ChevronDoubleUp20Filled as Up,
  ChevronDoubleDown16Filled as Down,
  Delete24Regular as Delete,
  NoteEdit24Regular as WriteDown
} from '@vicons/fluent'
import Preset from '../components/Preset.vue'
import { ref, toRaw, h, reactive } from 'vue'
import { v4 as uuid } from 'uuid'
import useGlobalStore from '../store/GlobalInfo'
const store = useGlobalStore()
const message = useMessage()
const modal = useModal()
const dialog = useDialog()

const active = ref(false)
const presetTitle = ref('')
const removeModal = ref(false)

// 操作逻辑
const copyData = (data) => () => {
  let result = []
  for (const v of data) {
    result.push(v.text)
  }
  result = result.join('\r\n')
  navigator.clipboard.writeText(result).then(() => {
    message.create('复制成功!', {
      type: 'success',
      duration: 2000
    })
  })
}

// 保存word逻辑
const saveData = (data) => async () => {
  let result = []
  for (const v of data) {
    result.push(v.doc)
  }
  await window.api.saveDocx(result).then((res) => {
    if (res.canceled) {
      message.create('取消保存!', {
        type: 'warning',
        duration: 4000
      })
    } else {
      message.create(`文件已保存在: ${res.savePath}`, {
        type: 'success',
        duration: 4000
      })
    }
  })
}

// 分页逻辑
const pagination = reactive({
  pageSize: 5,
  showSizePicker: false,
  // pageSizes: [3, 5, 7], // 显示的分页大小
  // pageSizes: [ 5],
  onChange: (page) => {
    pagination.page = page
  }
  // onUpdatePageSize: (pageSize) => {
  //   pagination.pageSize = pageSize;
  //   pagination.page = 1;
  // }
})

// 设置记录表格的列名
const historyCols = [
  {
    type: 'expand',
    // expandable: (rowData) => rowData.name !== "Jim Green", // 定义不展示的内容
    renderExpand: (rowData) => {
      return h(
        NFlex,
        { vertical: true },
        // 渲染栅格
        {
          default: () =>
            rowData.data.map((gridItem, index) => {
              // gridItem.data = gridItem.data.
              return h(
                NGrid,
                { cols: gridItem.cols, key: `${rowData.uuid}-${index}` },
                // 渲染栅格中的每个网格
                {
                  default: () =>
                    gridItem.data.map((gitem, i) =>
                      h(NGi, { key: `${rowData.uuid}-${index}-${i}` }, { default: () => gitem })
                    )
                }
              )
            })
        }
      )
    }
  },
  { title: '时间', key: 'date' },

  // { title: '内容', key: 'data'},
  {
    title: '操作',
    key: 'action',
    render: (row) => {
      return h(
        NFlex,
        {},
        {
          default: () => [
            h(
              NButton,
              { tertiary: true, onClick: () => (active.value = true) },
              { default: () => '查看' }
            ),
            h(NButton, { tertiary: true, onClick: saveData(row.data) }, { default: () => '保存' }),
            h(NButton, { tertiary: true, onClick: copyData(row.data) }, { default: () => '复制' })
          ]
        }
      )
    }
  }
]

// 保存预设
const savePreset = async () => {
  const newPreset = toRaw(store.todoTill)
  if (newPreset.length === 0) {
    message.create('没有预设内容，禁止输入空预设!', { type: 'warning', duration: 2000 })
    return false
  }
  dialog.info({
    title: '保存预设',
    content: () =>
      h(NInput, {
        value: presetTitle.value,
        onUpdateValue: (newValue) => (presetTitle.value = newValue),
        placeholder: '请输入预设名称',
        minlength: 4
      }),
    positiveText: '保存',
    negativeText: '取消',
    onPositiveClick: async () => {
      const p = await window.store.get('preset')
      if (Object.keys(p).includes(presetTitle.value)) {
        message.create('预设名已存在，重新输入预设名', { type: 'warning', duration: 2000 })
      } else {
        p[presetTitle.value] = newPreset
        await window.store.set('preset', p)
        await window.store.get('preset').then((res) => {
          store.config.preset = res
          presetTitle.value = ''
        })
      }
    }
  })
  // store.config.preset = await window.store.get('preset')
}

// 使用预设
const usePreset = async (item) => {
  console.log(item);
  store.todoTill.splice(0, store.todoTill.length);
  item.map((item) => {
    store.todoTill.push(item)
  })
}

// 删除预设
const removePreset = async (name) => {
  const path = `preset.${name}`
  await window.store.del(path)
  await window.store.get('preset').then((res) => {
    store.config.preset = res
  })
}

// 打开文件夹
const openFolder = () => {
  window.store.openFolder()
}

// 点击生成
const handleClick = async () => {
  store.isWorking = true // 开始工作
  store.todoTill.map((item) => {
    item.status = 'waiting'
  })
  // console.log('store.todoTill:', toRaw(store.todoTill));

  // 完成任务后要保存的信息
  const _data = {
    date: null,
    data: [],
    uuid: ''
  }
  // 依次执行任务
  for (const v of toRaw(store.todoTill)) {
    store.currentUUID = v.uuid
    await window.electron.ipcRenderer
      .invoke('use-tool', v)
      .then((res) => {
        // console.log('res:', res) // 处理数据
        _data.data.push({ data: res.data })
        const index = store.todoTill.findIndex((item) => item.uuid === res.uuid)
        store.todoTill[index].status = res.status // 更新完成状态
      })
      .catch((err) => {
        console.log(err.data)

        message.create(err.data, {
          type: 'error',
          duration: 2000
        })
      })
  }
  // 插入任务完成时间
  _data.date = new Date()
  _data.date = _data.date.toLocaleString()
  // 为每次任务设置一个uuid方便后续查找展示
  _data.uuid = uuid()
  store.data.push(_data)
  store.currentUUID = '' // 清空当前在工作的uuid
  // 弹出消息，用户友好
  message.create('所有任务完成!', {
    type: 'info',
    duration: 2000
  })
  store.isWorking = false // 结束工作
  console.log(store.getHistoryData)
  // console.log(JSON.stringify(store.getHistoryData))
}
const historyClick = () => {
  modal.create({
    style: {
      width: '500px',
      height: '500px',
      padding: '20px'
    },
    title: '生成记录',
    preset: 'card',
    content: () =>
      h(
        NConfigProvider,
        {},
        {
          default: () =>
            h(NDataTable, {
              id: 'drawer-target',
              columns: historyCols,
              data: store.getHistoryData,
              rowKey: (row) => row.uuid,
              pagination: pagination
            })
        }
      )
  })
}

// 点击移动顺序
const mvItem = (index, model) => {
  // model type
  // 0 上移 1 下移
  let tmp = store.todoTill[index]
  console.log(`将要移动${index + 1},模式为${model}`)
  switch (model) {
    case 'up':
      // 把元素换位前一元素，再将前一元素换为当前元素
      store.todoTill[index] = store.todoTill[index - 1]
      store.todoTill[index - 1] = tmp
      break
    case 'down':
      store.todoTill[index] = store.todoTill[index + 1]
      store.todoTill[index + 1] = tmp
      break
    default:
      console.log('无效操作')
      break
  }
}
const removeItem = (index) => {
  store.todoTill.splice(index, 1)
}

const loadingBarTargetRef = ref(void 0)
</script>

<template>
  <!-- <n-drawer
    v-model:show="active"
    :width="400"
    :height="20"
  >
    <n-drawer-content title="斯通纳">
      《斯通纳》是美国作家约翰·威廉姆斯在 1965 年出版的小说。
    </n-drawer-content>
  </n-drawer> -->
  <n-loading-bar-provider :to="loadingBarTargetRef" container-style="position: absolute;">
    <n-flex vertical style="height: 100%" class="sidebar">
      <div>
        <h2>预设</h2>
        <n-flex>
          <n-collapse arrow-placement="right" :default-expanded-names="['1']">
            <n-collapse-item title="预设" name="1">
              <Preset></Preset>
            </n-collapse-item>
            <n-collapse-item title="操作" name="2">
              <n-list hoverable clickable>
                <n-list-item>
                  <n-flex align="center" justify="center" @click="savePreset">
                    <n-icon :size="20"><WriteDown /></n-icon>
                    <n-text>保存预设</n-text>
                  </n-flex>
                </n-list-item>
                <n-list-item>
                  <n-flex align="center" justify="center" @click="removeModal = true">
                    <n-icon :size="20"><Delete /></n-icon>
                    <n-text>删除预设</n-text>
                  </n-flex>
                </n-list-item>
                <n-list-item>
                  <n-flex align="center" justify="center" @click="openFolder">
                    <n-icon :size="20"><FolderOpen /></n-icon>
                    <n-text>打开目录</n-text>
                  </n-flex>
                </n-list-item>
              </n-list>
            </n-collapse-item>
          </n-collapse>
        </n-flex>
      </div>

      <div>
        <n-flex align="center" justify="space-between">
          <h2>待办</h2>
          <n-flex class="action" justify="space-evenly">
            <n-button
              text
              :disabled="store.todoTill.length == 0 || store.isWorking"
              @click="handleClick"
              >生成</n-button
            >
            <n-button text @click="historyClick">记录</n-button>
            <n-button text @click="store.todoTill.splice(0, store.todoTill.length)">清除</n-button>
          </n-flex>
        </n-flex>
        <!-- 如果待办列表为空，则显示一个空内容组件 -->
        <n-empty v-if="store.todoTill.length == 0" style="margin-top: 30px">
          <template #default> 在右侧添加待办内容 </template>
          <template #icon>
            <n-icon>
              <AlertCircleSharp />
            </n-icon>
          </template>
        </n-empty>
        <!-- 否则出示列表 -->
        <n-list v-else>
          <!-- 待办列表项目 -->
          <n-list-item v-for="(item, index) in store.todoTill" :key="item.uuid">
            <n-alert
              @close="removeItem(index)"
              closable
              :show-icon="false"
              :type="
                !store.isWorking
                  ? 'default'
                  : item.status === 'waiting'
                    ? 'warning'
                    : item.status === 'success'
                      ? 'success'
                      : 'error'
              "
            >
              <n-thing>
                <!-- 标题 -->
                <template #header>{{ item.title }}</template>
                <!-- 判断是否完成此项任务 -->
                <template #header-extra>
                  <n-spin v-if="store.isWorking && item.status === 'waiting'" :size="18"></n-spin>
                  <n-icon></n-icon>
                </template>
                <!-- 底部操作 -->
                <template #action>
                  <n-flex>
                    <!-- 向上移动 -->
                    <n-button text @click="mvItem(index, 'up')" :disabled="index === 0">
                      <template #icon>
                        <n-icon :size="17"><Up /></n-icon>
                      </template>
                      上移
                    </n-button>
                    <!-- 向下移动 -->
                    <n-button
                      text
                      @click="mvItem(index, 'down')"
                      :disabled="index === store.todoTill.length - 1"
                    >
                      <template #icon>
                        <n-icon :size="17"><Down /></n-icon>
                      </template>
                      下移
                    </n-button>
                  </n-flex>
                </template>
              </n-thing>
            </n-alert>
          </n-list-item>
        </n-list>
      </div>
    </n-flex>

    <!-- 删除预设时候的modal -->
    <n-modal
      v-model:show="removeModal"
      class="custom-card"
      preset="card"
      :style="{ width: '500px', height: '300px' }"
      title="删除预设"
      :bordered="false"
    >
      <n-infinite-scroll style="height: 220px">
        <n-list>
          <n-list-item v-for="(_, name) in store.config.preset" :key="name">
            <n-flex justify="space-between" style="padding-right: 20px">
              <n-text>{{ name }}</n-text>
              <n-button @click="removePreset(name)" tertiary>删除</n-button>
            </n-flex>
          </n-list-item>
        </n-list>
      </n-infinite-scroll>
    </n-modal>
  </n-loading-bar-provider>
</template>
